﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Threading;
using System.Data;


namespace TierService
{
    public class StringHelper
    {
        public StringHelper()
        {

        }
        /// <summary>
        /// 获得一个16位时间随机数
        /// </summary>
        /// <returns>返回随机数</returns>
        public static string GetDataRandom()
        {
            string strData = DateTime.Now.ToString();
            strData = strData.Replace(":", "");
            strData = strData.Replace("-", "");
            strData = strData.Replace(" ", "");
            Random r = new Random();
            strData = strData + r.Next(100000);
            return strData;
        }
        /// <summary>
        ///  获得某个字符串在另个字符串中出现的次数
        /// </summary>
        /// <param name="strOriginal">要处理的字符</param>
        /// <param name="strSymbol">符号</param>
        /// <returns>返回值</returns>
        public static int GetStrCount(string strOriginal, string strSymbol)
        {
            int count = 0;
            for (int i = 0; i < (strOriginal.Length - strSymbol.Length + 1); i++)
            {
                if (strOriginal.Substring(i, strSymbol.Length) == strSymbol)
                {
                    count = count + 1;
                }
            }
            return count;
        }
        /// <summary>
        /// 获得某个字符串在另个字符串第一次出现时前面所有字符
        /// </summary>
        /// <param name="strOriginal">要处理的字符</param>
        /// <param name="strSymbol">符号</param>
        /// <returns>返回值</returns>
        public static string GetFirstStr(string strOriginal, string strSymbol)
        {
            int strPlace = strOriginal.IndexOf(strSymbol);
            if (strPlace != -1)
                strOriginal = strOriginal.Substring(0, strPlace);
            return strOriginal;
        }
        /// <summary>
        /// 获得某个字符串在另个字符串最后一次出现时后面所有字符
        /// </summary>
        /// <param name="strOriginal">要处理的字符</param>
        /// <param name="strSymbol">符号</param>
        /// <returns>返回值</returns>
        public static string GetLastStr(string strOriginal, string strSymbol)
        {
            int strPlace = strOriginal.LastIndexOf(strSymbol) + strSymbol.Length;
            strOriginal = strOriginal.Substring(strPlace);
            return strOriginal;
        }
        /// <summary>
        /// 获得两个字符之间第一次出现时前面所有字符
        /// </summary>
        /// <param name="strOriginal">要处理的字符</param>
        /// <param name="strFirst">最前哪个字符</param>
        /// <param name="strLast">最后哪个字符</param>
        /// <returns>返回值</returns>
        public static string GetTwoMiddleFirstStr(string strOriginal, string strFirst, string strLast)
        {
            strOriginal = GetFirstStr(strOriginal, strLast);
            strOriginal = GetLastStr(strOriginal, strFirst);
            return strOriginal;
        }
        /// <summary>
        ///  获得两个字符之间最后一次出现时的所有字符
        /// </summary>
        /// <param name="strOriginal">要处理的字符</param>
        /// <param name="strFirst">最前哪个字符</param>
        /// <param name="strLast">最后哪个字符</param>
        /// <returns>返回值</returns>
        public static string GetTwoMiddleLastStr(string strOriginal, string strFirst, string strLast)
        {
            strOriginal = GetLastStr(strOriginal, strFirst);
            strOriginal = GetFirstStr(strOriginal, strLast);
            return strOriginal;
        }
        /// <summary>
        /// 从数据库表读记录时,能正常显示
        /// </summary>
        /// <param name="strContent">要处理的字符</param>
        /// <returns>返回正常值</returns>
        public static string GetHtmlFormat(string strContent)
        {
            strContent = strContent.Trim();

            if (strContent == null)
            {
                return "";
            }
            strContent = strContent.Replace("<", "&lt;");
            strContent = strContent.Replace(">", "&gt;");
            strContent = strContent.Replace("\n", "<br />");
            //strContent=strContent.Replace("\r","<br>");
            return (strContent);
        }
        /// <summary>
        /// 检查相等之后，获得字符串
        /// </summary>
        /// <param name="str">字符串1</param>
        /// <param name="checkStr">字符串2</param>
        /// <param name="reStr">相等之后要返回的字符串</param>
        /// <returns>返回字符串</returns>
        public static string GetCheckStr(string str, string checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>
        /// 检查相等之后，获得字符串
        /// </summary>
        /// <param name="str">数值1</param>
        /// <param name="checkStr">数值2</param>
        /// <param name="reStr">相等之后要返回的字符串</param>
        /// <returns>返回字符串</returns>
        public static string GetCheckStr(int str, int checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>
        /// 检查相等之后，获得字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="checkStr"></param>
        /// <param name="reStr"></param>
        /// <returns></returns>
        public static string GetCheckStr(bool str, bool checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>
        /// 检查相等之后，获得字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="checkStr"></param>
        /// <param name="reStr"></param>
        /// <returns></returns>
        public static string GetCheckStr(object str, object checkStr, string reStr)
        {
            if (str == checkStr)
            {
                return reStr;
            }
            return "";
        }
        /// <summary>
        /// 截取左边规定字数字符串
        /// </summary>
        /// <param name="str">需截取字符串</param>
        /// <param name="length">截取字数</param>
        /// <param name="endStr">超过字数，结束字符串，如"..."</param>
        /// <returns>返回截取字符串</returns>
        public static string GetLeftStr(string str, int length, string endStr)
        {
            string reStr;
            if (length < GetStrLength(str))
            {
                reStr = str.Substring(0, length) + endStr;
            }
            else
            {
                reStr = str;
            }
            return reStr;
        }
        /// <summary>
        /// 截取左边规定字数字符串
        /// </summary>
        /// <param name="str">需截取字符串</param>
        /// <param name="length">截取字数</param>
        /// <returns>返回截取字符串</returns>
        public static string GetLeftStr(string str, int length)
        {
            string reStr;
            if (length < str.Length)
            {
                reStr = str.Substring(0, length) + "...";
            }
            else
            {
                reStr = str;
            }
            return reStr;
        }
        /// <summary>
        /// 获得双字节字符串的字节数
        /// </summary>
        /// <param name="str">要检测的字符串</param>
        /// <returns>返回字节数</returns>
        public static int GetStrLength(string str)
        {
            ASCIIEncoding n = new ASCIIEncoding();
            byte[] b = n.GetBytes(str);
            int l = 0;  // l 为字符串之实际长度
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] == 63)  //判断是否为汉字或全脚符号
                {
                    l++;
                }
                l++;
            }
            return l;
        }
        /// <summary>
        /// 剥去HTML标签
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string RegStripHtml(string text)
        {
            string reStr;
            string RePattern = @"<\s*(\S+)(\s[^>]*)?>";
            reStr = Regex.Replace(text, RePattern, string.Empty, RegexOptions.Compiled);
            reStr = Regex.Replace(reStr, @"\s+", string.Empty, RegexOptions.Compiled);
            return reStr;
        }
        /// <summary>
        /// 转换HTML与相对去处相对标签 未测试
        /// </summary>
        /// <param name="text"></param>
        /// <param name="ReLabel"></param>
        /// <returns></returns>
        public static string RegStripHtml(string text, string[] ReLabel)
        {
            string reStr = text;
            string LabelPattern = @"<({0})\s*(\S+)(\s[^>]*)?>[\s\S]*<\s*\/\1\s*>";
            string RePattern = @"<\s*(\S+)(\s[^>]*)?>";
            for (int i = 0; i < ReLabel.Length; i++)
            {
                reStr = Regex.Replace(reStr, string.Format(LabelPattern, ReLabel[i]), string.Empty, RegexOptions.IgnoreCase);
            }
            reStr = Regex.Replace(reStr, RePattern, string.Empty, RegexOptions.Compiled);
            reStr = Regex.Replace(reStr, @"\s+", string.Empty, RegexOptions.Compiled);
            return reStr;
        }
        /// <summary>
        /// 使Html失效,以文本显示
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <returns>失效后字符串</returns>
        public static string ReplaceHtml(string str)
        {
            str = str.Replace("<", "&lt");
            return str;
        }
        /// <summary>
        /// 获得随机数字
        /// </summary>
        /// <param name="Length">随机数字的长度</param>
        /// <returns>返回长度为 Length 的　<see cref="System.Int32"/> 类型的随机数</returns>
        /// <example>
        /// Length 不能大于9,以下为示例演示了如何调用 GetRandomNext：<br />
        /// <code>
        ///		int le = GetRandomNext(8);
        /// </code>
        /// </example>
        public static int GetRandomNext(int Length)
        {
            if (Length > 9)
                throw new System.IndexOutOfRangeException("Length的长度不能大于10");
            Guid gu = Guid.NewGuid();
            string str = "";
            for (int i = 0; i < gu.ToString().Length; i++)
            {
                if (isNumber(gu.ToString()[i]))
                {
                    str += ((gu.ToString()[i]));
                }
            }
            int guid = int.Parse(str.Replace("-", "").Substring(0, Length));
            if (!guid.ToString().Length.Equals(Length))
                guid = GetRandomNext(Length);
            return guid;
        }
        /// <summary>
        /// 返回一个 bool 值，指明提供的值是不是整数
        /// </summary>
        /// <param name="obj">要判断的值</param>
        /// <returns>true[是整数]false[不是整数]</returns>
        /// <remarks>
        ///		isNumber　只能判断正(负)整数，如果 obj 为小数则返回 false;
        /// </remarks>
        /// <example>
        /// 下面的示例演示了判断 obj 是不是整数：<br />
        /// <code>
        ///		bool flag;
        ///		flag = isNumber("200");
        /// </code>
        /// </example>
        public static bool isNumber(object obj)
        {
            //为指定的正则表达式初始化并编译 Regex 类的实例
            System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^-?(\d*)$");
            //在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式匹配项
            System.Text.RegularExpressions.Match mc = rg.Match(obj.ToString());
            //指示匹配是否成功
            return (mc.Success);
        }
        /// <summary>
        /// 高亮显示
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="findstr">查找字符串</param>
        /// <param name="cssclass">Style</param>
        /// <returns></returns>
        public static string OutHighlightText(string str, string findstr, string cssclass)
        {
            if (findstr != "")
            {
                string text1 = "<span class=\"" + cssclass + "\">%s</span>";
                str = str.Replace(findstr, text1.Replace("%s", findstr));
            }
            return str;
        }


        #region 去除HTML标签函数
        public string RemoveHtmlCode(string _html)//去除HTML标签函数
        {
            string strOutput = _html;
            Regex regex = new Regex(@"<.+?>", RegexOptions.IgnoreCase);
            strOutput = regex.Replace(strOutput, "");
            return strOutput;
        }
        #endregion


        /// <summary>
        /// 去除html标签
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string OutHtmlText(string str)
        {
            string text1 = "<.*?>";
            Regex regex1 = new Regex(text1);
            str = regex1.Replace(str, "");
            str = str.Replace("[$page]", "");
            str = str.Replace("&nbsp;", "");
            return ToHtmlText(str);
        }
        /// <summary>
        /// 将html显示成文本
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToHtmlText(string str)
        {
            if (str == "")
            {
                return "";
            }
            StringBuilder builder1 = new StringBuilder();
            builder1.Append(str);
            builder1.Replace("<", "&lt;");
            builder1.Replace(">", "&gt;");
            //builder1.Replace("\r", "<br>");
            return builder1.ToString();
        }
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="strInput">输入字符串</param>
        /// <param name="intLen"></param>
        /// <returns></returns>
        public static string CutString(string strInput, int intLen)
        {
            strInput = strInput.Trim();
            byte[] buffer1 = Encoding.Default.GetBytes(strInput);
            if (buffer1.Length > intLen)
            {
                string text1 = "";
                for (int num1 = 0; num1 < strInput.Length; num1++)
                {
                    byte[] buffer2 = Encoding.Default.GetBytes(text1);
                    if (buffer2.Length >= (intLen - 4))
                    {
                        break;
                    }
                    text1 = text1 + strInput.Substring(num1, 1);
                }
                return (text1 + "...");
            }
            return strInput;
        }
        /// <summary>
        /// 根据条件返回值
        /// </summary>
        /// <param name="ifValue"></param>
        /// <param name="trueValue"></param>
        /// <param name="falseVale"></param>
        /// <returns></returns>
        public static string IfValue(bool ifValue, string trueValue, string falseVale)
        {
            if (ifValue)
            {
                return trueValue;
            }
            return falseVale;
        }

        #region //首字母大写
        public static string ToTitleCase(string str)
        {
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo textInfo = cultureInfo.TextInfo;
            return textInfo.ToTitleCase(str);
        }
        #endregion

        #region 截取字符串前N个字符
        public String DoTrim(String f2_lasttopic, int intlength)//截取字符串前N个字符
        {
            try
            {
                if (f2_lasttopic == "")
                {
                    return "";//可以任意写
                }
                else
                {
                    if (f2_lasttopic.Length > intlength)
                    {
                        return f2_lasttopic.Substring(0, intlength) + "..";
                    }
                    else
                    {
                        return f2_lasttopic;
                    }
                }
            }
            catch (Exception) { return ""; }
        }
        #endregion

        #region 截取字符串前N个字符
        public String DoTrimx(String f2_lasttopic, int intlength)//截取字符串前N个字符
        {
            try
            {
                if (f2_lasttopic == "")
                {
                    return "";//可以任意写
                }
                else
                {
                    if (f2_lasttopic.Length > intlength)
                    {
                        return f2_lasttopic.Substring(0, intlength);
                    }
                    else
                    {
                        return f2_lasttopic;
                    }
                }
            }
            catch (Exception) { return ""; }
        }
        #endregion

        /// <summary>
        /// 截取字符串最后的数字（用在自动编号的时候）
        /// </summary>
        /// <param name="lstr">原字符串</param>
        /// <returns>数字字符串</returns>
        public static string NOCutNumber(string lstr)
        {
            if (lstr == "")
            {
                return "0";
            }
            for (int i = 0; i < lstr.Length; i++)
            {
                string ochar = lstr.Remove(0, lstr.Length - i - 1);
                try
                {
                    long.Parse(ochar);
                    continue;
                }
                catch (Exception)
                {
                    return lstr.Remove(0, lstr.Length - i);
                }
            }
            return lstr;
        }

        /// <summary>
        /// 截取前面字符串（用在自动编号的时候）
        /// </summary>
        /// <param name="lstr">原字符串</param>
        /// <returns>数字字符串</returns>
        public static string NOCutString(string lstr)
        {
            if (lstr == "")
            {
                return "";
            }
            for (int i = 0; i < lstr.Length; i++)
            {
                string ochar = lstr.Remove(0, lstr.Length - i - 1);
                try
                {
                    long.Parse(ochar);
                    continue;
                }
                catch (Exception)
                {
                    return lstr.Remove(lstr.Length - i);
                }
            }
            return "";
        }

        #region "按字符串位数补0"
        /// <summary>
        /// 按字符串位数补0
        /// </summary>
        /// <param name="CharTxt">字符串</param>
        /// <param name="CharLen">字符长度</param>
        /// <returns></returns>
        public static string FillZero(string CharTxt, int CharLen)
        {
            if (CharTxt.Length < CharLen)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < CharLen - CharTxt.Length; i++)
                {
                    sb.Append("0");
                }
                sb.Append(CharTxt);
                return sb.ToString();
            }
            else
            {
                return CharTxt;
            }
        }
        /// <summary>
        ///  按字符串位数补上所要的字符
        /// </summary>
        /// <param name="strText">字符串</param>
        /// <param name="length">字符长度</param>
        /// <param name="strChar">字符</param>
        /// <returns></returns>
        public static string FillCharacter(string strText,int length,string strChar)
        {
            if (strText.Length < length)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < length - strText.Length; i++)
                {
                    sb.Append(strChar);
                }
                sb.Append(strText);
                return sb.ToString();
            }
            else
            {
                return strText;
            }
        }
        #endregion

        #region "按字符将一个字符串分割成一个字符数组，实现split"
        /// <summary>
        /// 按字符将一个字符串分割成一个字符数组，实现split
        /// </summary>
        /// <param name="strText">要分割的字符串</param>
        /// <param name="strChar">使用的字符</param>
        /// <returns></returns>
        public static string[] SplitString(string strText,string strChar)
        {
            string input = strText;
            string pattern = strChar;            // Split on hyphens
            string[] substrings = Regex.Split(input, pattern);
            return substrings;
        }

        #endregion


        #region 汉字转拼音
        /// <summary> 
        /// 取单个字符的拼音声母 
        /// zengdl
        /// 2008-06-10 
        /// </summary> 
        /// <param name="c">要转换的单个汉字</param> 
        /// <returns>拼音声母</returns> 
        public static string GetPYChar(string c)
        {
            byte[] array = new byte[2];
            array = System.Text.Encoding.Default.GetBytes(c);
            int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
            if (i < 0xB0A1) return "*";
            if (i < 0xB0C5) return "a";
            if (i < 0xB2C1) return "b";
            if (i < 0xB4EE) return "c";
            if (i < 0xB6EA) return "d";
            if (i < 0xB7A2) return "e";
            if (i < 0xB8C1) return "f";
            if (i < 0xB9FE) return "g";
            if (i < 0xBBF7) return "h";
            if (i < 0xBFA6) return "g";
            if (i < 0xC0AC) return "k";
            if (i < 0xC2E8) return "l";
            if (i < 0xC4C3) return "m";
            if (i < 0xC5B6) return "n";
            if (i < 0xC5BE) return "o";
            if (i < 0xC6DA) return "p";
            if (i < 0xC8BB) return "q";
            if (i < 0xC8F6) return "r";
            if (i < 0xCBFA) return "s";
            if (i < 0xCDDA) return "t";
            if (i < 0xCEF4) return "w";
            if (i < 0xD1B9) return "x";
            if (i < 0xD4D1) return "y";
            if (i < 0xD7FA) return "z";

            return "*";
        }

        /// <summary> 
        /// 汉字转拼音缩写 
        /// zengdl
        /// 2008-06-10 
        /// </summary> 
        /// <param name="str">要转换的汉字字符串</param> 
        /// <returns>拼音缩写</returns> 
        public static string GetPYString(string str)
        {
            string tempStr = "";
            foreach (char c in str)
            {
                if ((int)c >= 33 && (int)c <= 126)
                {//字母和符号原样保留 
                    tempStr += c.ToString();
                }
                else
                {//累加拼音声母 
                    tempStr += GetPYChar(c.ToString());
                }
            }
            return tempStr;
        }
        #endregion


    }
}
